package internal

import (
	"CaptchaCluster/defineMsg"
	"CaptchaCluster/log"
	"github.com/name5566/leaf/gate"
	"reflect"
)

func init() {
	handler(&defineMsg.ReqPong{}, handleReqPong)
	handler(&defineMsg.ReqMachineInfo{}, handleReqMachineInfo)
	handler(&defineMsg.ReqMachineName{}, handleReqMachineName)
}

func handler(m interface{}, h interface{}) {
	skeleton.RegisterChanRPC(reflect.TypeOf(m), h)
}

func handleReqPong(args []interface{}) {
	a := args[1].(gate.Agent)

	data, ok := conns.Load(a)
	if !ok {
		a.Close()
	} else {
		data.(*MachineData).Pong <- true
		heartbeat(a)
	}
}

func handleReqMachineInfo(args []interface{}) {
	m := args[0].(*defineMsg.ReqMachineInfo)
	a := args[1].(gate.Agent)

	_ = m
	_ = a

	data, _ := conns.Load(a)
	machineData := data.(*MachineData)
	machineData.MachineInfo = append(machineData.MachineInfo, *m)
	conns.Store(a, machineData)
}

func handleReqMachineName(args []interface{}) {
	m := args[0].(*defineMsg.ReqMachineName)
	a := args[1].(gate.Agent)

	_ = m
	_ = a

	data, _ := conns.Load(a)
	machineData := data.(*MachineData)
	machineData.Name = m.Name
	conns.Store(a, machineData)
	log.Release("the name of %s is %s", a.RemoteAddr().String(), m.Name)
}
